﻿using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using System;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for ProductionOrder.xaml
    /// </summary>
    public partial class YGRABHM :UserControl
    {
        bool IsLoaded = false;
        #region-------------Properties-----------------------

        YGRABDOCData MainViewModel;
        ITXEXRPT ITXEXRPT;
        public ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        INTEXDBC INTEXDBC
        {
            get
            {
                return app.INTEXDBC;
            }
        }
        public INTEXBL INTEXBL
        {
            get
            {
                return app.INTEXBL;
            }
        }
        public SETINTEXDB SetMaster
        {
            get
            {
                return MainViewModel.SetMaster;
            }
        }
        public SETINTEXDB SetDetail
        {
            get
            {
                return MainViewModel.SetMaster;
            }
        }
        public SETINTEXDB SetEnv
        {
            get
            {
                return MainViewModel.SetMaster;
            }
        }
        public SETINTEXDB SetStock
        {
            get
            {
                return MainViewModel.SetMaster;
            }
        }

        #region=====vwABPOS=======
        CollectionViewSource vwABPOS
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABPOS");
            }
        }
        DataRow dwMaster
        {
            get
            {
                if (vwABPOS.View == null)
                    return null;
                if ((DataRowView)vwABPOS.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABPOS.View.CurrentItem).Row;
            }
        }
        #endregion

        #region=====vwGAAUF=======
        CollectionViewSource vwGAAUF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwGAAUF");
            }
        }
        DataRow dwGAAUF
        {
            get
            {
                if (vwGAAUF.View == null)
                    return null;
                if ((DataRowView)vwGAAUF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwGAAUF.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====vwMU=======
        CollectionViewSource vwMU
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwMU");
            }
        }
        DataRow dwMU
        {
            get
            {
                if (vwMU.View == null)
                    return null;
                if ((DataRowView)vwMU.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwMU.View.CurrentItem).Row;
            }
        }
        #endregion
        #region=====  vwYGAAUF=======
        CollectionViewSource vwYGAAUF
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwYGAAUF");
            }
        }
        DataRow dwYGAAUF
        {
            get
            {
                if (vwYGAAUF.View == null)
                    return null;
                if ((DataRowView)vwYGAAUF.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwYGAAUF.View.CurrentItem).Row;
            }
        }
        #endregion

        public string KRS
        {
            get
            {
                return Helpers.Helper.Right("  " + txtAUFKRS.Text.ToString().Trim(), 2);
            }
            set
            {
                txtAUFKRS.Text = value;
            }
        }
        public string LFD
        {
            get
            {
                return Helpers.Helper.Right("000000" + txtAUFLFD.Text.ToString().Trim(), 6); ;
            }
            set
            {
                txtAUFLFD.Text = value;
            }
        }
        string POS
        {
            get
            {
                return Helpers.Helper.Right("000" + txtAUFPOS.Text.ToString().Trim(), 3); ;
            }
            set
            {
                txtAUFPOS.Text = value;
            }
        }
        decimal BatchQty
        {
            get
            {
                if (txtBatchQty.Text.Trim() == "")
                    txtBatchQty.Text = "0";
                return Convert.ToDecimal(txtBatchQty.Text.ToString());
            }
            set
            {
                txtBatchQty.Text = value.ToString();
            }
        }
        decimal Batches
        {
            get
            {
                if (txtBatches.Text.Trim() == "")
                    txtBatches.Text = "0";
                return Convert.ToDecimal(txtBatches.Text.ToString());
            }
            set
            {
                txtBatches.Text = value.ToString();
            }
        }

        double ABPQTY
        {
            get
            {
                if (dwMaster == null)
                    return 0;
                return Convert.ToDouble(dwMaster["ABPSOLLMENGE5"].ToString()) / 100;
            }
        }

 
        BindingListCollectionView cvGAAUF
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(this.dlgABP.ItemsSource);
            }
        } 

        #endregion
        public YGRABHM()
        {
            
            InitializeComponent();
            this.Name = "纺纱生产";
            
            ITXEXRPT = new ITXEXRPT();
            ITXEXRPT.Root = "C:\\IntexReport";
            ITXEXRPT.strCompany = app.company;
            ITXEXRPT.PrintType = "OpenExcel";
     
        } 
        
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (DesignerProperties.GetIsInDesignMode(this))
                    return;
                if (IsLoaded)
                    return;
                IsLoaded = true;
                MainViewModel=DataContext as YGRABDOCData;
                MainViewModel.LoadEnv();
                vwABPOS.View.CurrentChanged += vwABPOS_CurrentChanged;
                vwMU.View.CurrentChanged += vwMU_CurrentChanged;
                vwGAAUF.View.CurrentChanged += vwGAAUF_CurrentChanged;
                KRS = "HM";
                LFD = "000014";
                BatchQty = Convert.ToDecimal(0);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;

        }
        void vwGAAUF_CurrentChanged(object sender, EventArgs e)
        {
            if (dwGAAUF == null)
                return;
            var qTotal = (from GA in SetDetail.Tables["GAAUF"].AsEnumerable()
                          where GA["GASA"].ToString() == "713"
                          select Convert.ToDouble(GA["GABASMG2"].ToString())).Sum();
            double Total = (double)qTotal;
            txtTRatio.Text = (Total / 1000).ToString(); 
        }
      
        void vwMU_CurrentChanged(object sender, EventArgs e)
        {
            if (dwMU == null)
                return;
            string ABAAPOS = dwMU["ABAAPOS"].ToString();
            var qMU = from MUrow in SetDetail.Tables["ICC_ABAX"].AsEnumerable()
                      group MUrow by new
                      {
                          KRS = MUrow["ABAAUFKRS"].ToString(),
                          LFD = MUrow["ABAAUFLFD"].ToString(),
                          APOS = MUrow["ABAAPOS"].ToString(),
                      }
                          into g
                          select new
                          {
                              KEY = g.Key,
                              BATCHES = g.Max(XD => Convert.ToDouble(XD["ABAVKFARBE"].ToString())),
                              MQTY = g.Sum(XD => Convert.ToDouble(XD["ABARESMG"].ToString()) / 1000),
                          };
            foreach (var mu in qMU)
            {
                if (mu.KEY.APOS == ABAAPOS)
                {
                    BatchQty = Convert.ToDecimal(mu.MQTY);
                    Batches = Convert.ToDecimal(mu.BATCHES);
                }
            }
        }
        
        void vwABPOS_CurrentChanged(object sender, EventArgs e)
        {
            if (dwMaster == null)
                return;
            DataTable tb = null;
            try
            {
                SetDetail.Merge(SetMaster);
                SetDetail.Clear();
                SetDetail.Merge(SetMaster.Tables["ABKOPF"]);
                SetDetail.Merge(SetMaster.Tables["GSDAT"]);
                SetDetail.Merge(SetMaster.Tables["GSCOLOR"]);
                SetDetail.Merge(SetMaster.Tables["GSMATK"]);
                SetDetail.Merge(SetMaster.Tables["TBABA"]);
                if (SetMaster.Tables.Contains("VKPOS"))
                {
                    SetDetail.Merge(SetMaster.Tables["VKPOS"]);
                }

                DataRow[] rows = SetMaster.ABPOS.Select("ABPAUFPOS='" + dwMaster["ABPAUFPOS"].ToString() + "'");
                tb = rows.CopyToDataTable();
                tb.TableName = "ABPOS";
                SetDetail.Merge(tb);
                rows = SetMaster.ABFOLGE.Select("ABFAUFPOS='" + dwMaster["ABPAUFPOS"].ToString() + "'");
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "ABFOLGE";
                    SetDetail.Merge(tb);
                }
                rows = SetMaster.GAAUF.Select("GAAUFPOS='" + dwMaster["ABPAUFPOS"].ToString() + "'");
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "GAAUF";
                    SetDetail.Merge(tb);
                    RefreshRatio();
                }
                rows = SetMaster.Tables["ZUTEI"].Select("ZUAUFPOS='" + dwMaster["ABPAUFPOS"].ToString() + "'");
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "ZUTEI";
                    SetDetail.Merge(tb);
                    dlgZUTEI.Visibility = Visibility.Visible;
                    dlgZUTEIEXT.Visibility = Visibility.Collapsed;
                }

                rows = SetMaster.Tables["ZUTEI_ITX"].Select("ZUAUFPOS='" + dwMaster["ABPAUFPOS"].ToString() + "'");
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "ZUTEI_ITX";
                    SetDetail.Merge(tb);
                }

                rows = SetMaster.Tables["ZUTEI_EXT"].Select("ABAVKAUFLFD='" + dwMaster["ABPAUFLFD"].ToString() + "' AND ABAVKAUFPOS='" + dwMaster["ABPAUFPOS"].ToString() + "'");
                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    tb.TableName = "ZUTEI_EXT";
                    SetDetail.Merge(tb);
                    dlgZUTEI.Visibility = Visibility.Collapsed;
                    dlgZUTEIEXT.Visibility = Visibility.Visible;
                }
                btnInitializedMU.IsEnabled = true;
                btnRemoveBatch.IsEnabled = false;
                btnAddBatch.IsEnabled = false;
                rows = SetMaster.Tables["ABAUFM"].Select("ABAVKAUFLFD='" + dwMaster["ABPAUFLFD"].ToString() + "' AND ABAVKAUFPOS='" + dwMaster["ABPAUFPOS"].ToString() + "'");

                if (rows.Length > 0)
                {
                    tb = rows.CopyToDataTable();
                    btnInitializedMU.IsEnabled = false;
                    btnRemoveBatch.IsEnabled = true;
                    btnAddBatch.IsEnabled = true;
                    tb.TableName = "ABAUFM";
                    SetDetail.Merge(tb);
                    tb.TableName = "ICC_ABAX";
                    SetDetail.Merge(tb);
                }

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
                if (tb.TableName == "ABAUFM")
                {
                    SetDetail.Tables["ICC_ABAX"].Clear();
                    tb.TableName = "ICC_ABAX";
                    SetDetail.Merge(tb);
                }
            }
            finally
            {

            }
        }
        private void RefreshRatio()
        {
            var qTotal = (from GA in SetDetail.Tables["GAAUF"].AsEnumerable()
                          where GA["GASA"].ToString() == "713"
                          select Convert.ToDouble(GA["GAKG1"].ToString())).Sum();
            double Total = (double)qTotal;
            double TRatio = 0;
            foreach (DataRow row in SetDetail.Tables["GAAUF"].Rows)
            {
                double bom = Convert.ToDouble(row["GABASMG2"].ToString());
                TRatio += bom / 1000;
            }
            txtTRatio.Text = TRatio.ToString();
        }
        private void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                SetDetail.Clear();
                DataSet Result = new DataSet();
                using (new LongOperation(this, "正在生成报表，请耐心等待"))
                {
                 MainViewModel.BuildData("00", KRS, LFD);
                }
                
                if (vwABPOS != null)
                {
                    if (vwABPOS.View != null)
                    {
                        vwABPOS.View.MoveCurrentTo(-1);
                    }
                }
                if (vwABPOS.View != null)
                {
                    vwABPOS.View.MoveCurrentToFirst();
                }
                cvGAAUF.CustomFilter = "GASA='713'";
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnPrintGB12_Click(object sender, EventArgs e)
        {
            ITXEXRPT.dsSource = SetDetail;
            ITXEXRPT.dsSource.Merge(SetEnv);
            ITXEXRPT.DocType = app.company + "AB50GB12";
            ITXEXRPT.strExcelFile = app.company + @"\YGRABDOC.xls";
            string filename = ITXEXRPT.WriteExcelReport();
        }

        private void btnPrintBatches_Click(object sender, RoutedEventArgs e)
        {
            ITXEXRPT.dsSource = SetDetail;
            ITXEXRPT.dsSource.Merge(SetEnv);
            ITXEXRPT.DocType = app.company + "AB50GB20";
            ITXEXRPT.strExcelFile = app.company + @"\YGRABDOC.xls";
            string filename = ITXEXRPT.WriteExcelReport();
        }
        private void btnPrintABDOC_Click(object sender, RoutedEventArgs e)
        {
            ITXEXRPT.dsSource = SetDetail;
            ITXEXRPT.dsSource.Merge(SetEnv);
            ITXEXRPT.DocType = app.company + "AB50DOC";
            ITXEXRPT.strExcelFile = app.company + @"\YGRABDOC.xls";
            string filename = ITXEXRPT.WriteExcelReport();
        }

        private void btnPrintAR_Click(object sender, RoutedEventArgs e)
        {

            ITXEXRPT.dsSource = SetMaster;
            ITXEXRPT.dsSource.Merge(SetEnv);
            ITXEXRPT.DocType = app.company + "AB50AR";
            ITXEXRPT.strExcelFile = app.company + @"\YGRABDOC.xls";
            string filename = ITXEXRPT.WriteExcelReport();
        }
        private void txtAUFLFD_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                //btnQuery_Click(null, null);
            }
        }

        private void btnInitializedMU_Click(object sender, RoutedEventArgs e)
        {
            if (dwMaster == null)
            {
                MessageBox.Show("请选择需要计划的生产单单");
                return;
            }
            DataSet SResult;
            SetDetail.ICC_ABAX.Clear();
            //正对所有的单创建一个记录集合，针对每个单的记录集合，创建生产单
            SResult = MainViewModel.PrePlan(SetDetail, dwMaster);
            try
            {
                string path = @"C:\IntexReport\Data\YGRMU";
                SResult.Tables["ABPOS"].TableName = "ABPOS_EXT";
                INTEXBL.Save2Xml(SResult, path);
                INTEXBL.AutoConvert(path, "YGRMUZT");
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                MessageBox.Show("初始化完成之后，请执行查询");
            }
        }

        private void btnRemoveBatch_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var qMU = from row in SetDetail.ICC_ABAX.AsEnumerable()
                          group row by new
                           {
                               KRS = row["ABAAUFKRS"].ToString(),
                               LFD = row["ABAAUFLFD"].ToString(),
                               POS = row["ABAAUFPOS"].ToString(),
                           }
                              into g
                              select new
                              {
                                  KEY = g.Key,
                                  MQTY = g.Sum(XD => Convert.ToDecimal(XD["ABARESMG"].ToString()) / 1000),
                                  ABAAPOS = g.Max(XD => Convert.ToInt16(XD["ABAAPOS"].ToString())),
                              };
                foreach (var mu in qMU)
                {
                    int ABAAPOS = mu.ABAAPOS;
                    if (ABAAPOS == 2)
                    {
                        MessageBox.Show("最有一个，不可以在取消,若要继续删除，请使用根除功能");
                        return;
                    }
                    int ABALEAPOS = ABAAPOS - 1;
                    //find the row to split
                    var qExt = from DataRow row in SetDetail.ABAUFM.AsEnumerable()
                               where row["ABAAUFKRS"].ToString() == mu.KEY.KRS
                               && row["ABAAUFLFD"].ToString() == mu.KEY.LFD
                               && row["ABAAUFPOS"].ToString() == mu.KEY.POS
                               && Convert.ToInt16(row["ABAAPOS"].ToString()) == ABAAPOS
                               select row;
                    foreach (DataRow row in qExt)
                    {
                        decimal mqty = Convert.ToDecimal(row["ABARESMG"].ToString());
                        var qPre = from DataRow rPre in SetDetail.ABAUFM.AsEnumerable()
                                   where rPre["ABAAUFKRS"].ToString() == mu.KEY.KRS
                                   && rPre["ABAAUFLFD"].ToString() == mu.KEY.LFD
                                   && rPre["ABAAUFPOS"].ToString() == mu.KEY.POS
                                   && Convert.ToInt16(rPre["ABAAPOS"].ToString()) == ABAAPOS - 1
                                   select rPre;
                        foreach (DataRow rPre in qPre)
                        {
                            rPre["ABARESMG"] = Convert.ToDecimal(rPre["ABARESMG"].ToString()) + mqty;
                            INTEXDBC.UpdateABAUFM(rPre, 5);
                            INTEXDBC.DeleteABAUFM(row, 1);
                            row["ABAAPOS"] = "0001";
                            row["ABALEAPOS"] = ABALEAPOS;
                            INTEXDBC.UpdateABAUFM(row, 4);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private void btnRemoveMU_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwMU == null)
                    MessageBox.Show("请选择最大的分批号");
                string VKKRS = "", VKLFD = "", VKPOS = "";
                var qMU = from row in SetDetail.ICC_ABAX.AsEnumerable()
                          group row by new
                          {
                              KRS = row["ABAVKAUFKRS"].ToString(),
                              LFD = row["ABAVKAUFLFD"].ToString(),
                              POS = row["ABAVKAUFPOS"].ToString(),
                          }
                              into g
                              select new
                              {
                                  KEY = g.Key,
                                  MQTY = g.Sum(XD => Convert.ToDecimal(XD["ABARESMG"].ToString()) / 1000),
                                  ABAAPOS = g.Max(XD => Convert.ToInt16(XD["ABAAPOS"].ToString())),
                              };
                foreach (var mu in qMU)
                {
                    int ABAAPOS = mu.ABAAPOS;
                    VKKRS = mu.KEY.KRS;
                    VKLFD = mu.KEY.LFD;
                    VKPOS = mu.KEY.POS;
                    if (ABAAPOS > 2)
                    {
                        return;
                    }
                }
                DataRow dwData = SetMaster.ICC_QUERYTB.NewRow();
                dwData["GAMANDANT"] = dwMU["ABAMANDANT"];
                dwData["GAAUFKRS"] = dwMU["ABAAUFKRS"];
                dwData["GAAUFLFD"] = dwMU["ABAAUFLFD"];
                DataSet SResult = INTEXDBC.QueryGAAUF(dwData, 6);
                foreach (DataRow gaauf in SResult.Tables[0].Rows)
                {
                    gaauf["GAAUFKRS"] = VKKRS;
                    gaauf["GAAUFLFD"] = VKLFD;
                    gaauf["GAAUFPOS"] = VKPOS;
                    INTEXDBC.UpdateGAAUF(gaauf, 4);
                }
                var qZU = from DataRow ZU in SetDetail.Tables["ZUTEI_EXT"].AsEnumerable()
                          select ZU;
                foreach (DataRow ZU in qZU)
                {
                    ZU["ZUAUFKRS"] = VKKRS;
                    ZU["ZUAUFLFD"] = VKLFD;
                    ZU["ZUAUFPOS"] = VKPOS;
                    INTEXDBC.SaveZUTEI(ZU, "YGR");
                }
                INTEXBL.DELTEABPOS("00", dwMU["ABAAUFKRS"].ToString(), dwMU["ABAAUFLFD"].ToString(), "000");
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        //原有缸的分盘数和单盘重
        private void NewBatch(decimal batchqty, decimal batches)
        {
            decimal ratio = 1;
            decimal MQTY = 1;
            try
            {
                string CABAAPOS = dwMU["ABAAPOS"].ToString();
                var qMU = from row in SetDetail.ICC_ABAX.AsEnumerable()
                          group row by new
                          {
                              KRS = row["ABAAUFKRS"].ToString(),
                              LFD = row["ABAAUFLFD"].ToString(),
                              ABAAPOS = row["ABAAPOS"].ToString(),
                          }
                              into g
                              select new
                              {
                                  KEY = g.Key,
                                  MQTY = g.Sum(XD => Convert.ToDecimal(XD["ABARESMG"].ToString()) / 1000),
                              };
                foreach (var mu in qMU)
                {
                    if (mu.KEY.ABAAPOS == CABAAPOS)
                    {
                        MQTY = mu.MQTY;
                        ratio = batchqty / MQTY;
                    }
                }
                var qMUMx = from row in SetDetail.ICC_ABAX.AsEnumerable()
                            group row by new
                             {
                                 KRS = row["ABAAUFKRS"].ToString(),
                                 LFD = row["ABAAUFLFD"].ToString(),
                                 POS = row["ABAAUFPOS"].ToString(),
                             }
                                into g
                                select new
                                {
                                    KEY = g.Key,
                                    MQTY = g.Sum(XD => Convert.ToDecimal(XD["ABARESMG"].ToString()) / 1000),
                                    ABAAPOS = g.Max(XD => Convert.ToInt16(XD["ABAAPOS"].ToString())),
                                };
                int ABALEAPOS = 2;
                int ABAAPOS = 2;
                foreach (var mu in qMUMx)
                {
                    ABAAPOS = mu.ABAAPOS;
                    ABALEAPOS = ABAAPOS + 1;
                }
                //find the row to split
                var qExt = from DataRow row in SetDetail.ABAUFM.AsEnumerable()
                           where row["ABAAUFKRS"].ToString() == dwMU["ABAAUFKRS"].ToString()
                           && row["ABAAUFLFD"].ToString() == dwMU["ABAAUFLFD"].ToString()
                           && row["ABAAPOS"].ToString() == CABAAPOS
                           select row;
                foreach (DataRow row in qExt)
                {
                    if (row["ABAVKFARBE"].ToString().Trim() == "")
                        row["ABAVKFARBE"] = "1";
                    batches = Convert.ToDecimal(row["ABAVKFARBE"].ToString());
                    decimal mqty = Convert.ToDecimal(row["ABARESMG"].ToString()) / 1000;
                    DataRow nMu = INTEXDBC.Convert2ABAUFM(row, "YGR", true);//现在的留位行，表达为新增数量
                    nMu["ABARESMG"] = Math.Round(mqty * ratio * 1000 / 10) * 10;
                    nMu["ABAVKFARBE"] = 1;//分缸数
                    nMu["ABAVKART"] = nMu["ABARESMG"];//单盘重量
                    INTEXDBC.UpdateABAUFM(nMu, 3);
                    nMu = INTEXDBC.Convert2ABAUFM(row, "YGR", true);//新的留位行
                    nMu["ABARESMG"] = Math.Round(mqty * (1 - ratio) * 1000 / 10) * 10;
                    decimal ABARESMG = Convert.ToDecimal(nMu["ABARESMG"].ToString());
                    batchqty = Math.Round((ABARESMG / 10) / batches, 0) * 10;
                    nMu["ABAVKART"] = Helpers.Helper.Left(batchqty.ToString().PadRight(20), 20);//单盘重量
                    nMu["ABAAPOS"] = Helpers.Helper.Right("0000" + (ABALEAPOS).ToString(), 4);
                    INTEXDBC.SaveABAUFM(nMu, "YGR");
                    nMu["ABAAPOS"] = "0001";
                    nMu["ABALEAPOS"] = ABALEAPOS;
                    INTEXDBC.UpdateABAUFM(nMu, 4);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }
        private void UpdateBatches(decimal batches)
        {
            try
            {
                var qMU = from row in SetDetail.ICC_ABAX.AsEnumerable()
                          where row["ABAAPOS"].ToString() == dwMU["ABAAPOS"].ToString()
                          group row by new
                          {
                              KRS = row["ABAAUFKRS"].ToString(),
                              LFD = row["ABAAUFLFD"].ToString(),
                              POS = row["ABAAUFPOS"].ToString(),
                              ABAAPOS = row["ABAAPOS"].ToString(),
                          }
                              into g
                              select new
                              {
                                  KEY = g.Key,
                                  MQTY = g.Sum(XD => Convert.ToDecimal(XD["ABARESMG"].ToString())),
                              };
                foreach (var mu in qMU)
                {
                    decimal MQTY = mu.MQTY;
                    decimal targetmqty = Math.Round((MQTY / 10) / Batches, 0) * 10;
                    string ABAAPOS = mu.KEY.ABAAPOS;
                    //find the row to split
                    var qExt = from DataRow row in SetDetail.ABAUFM.AsEnumerable()
                               where row["ABAAUFKRS"].ToString() == mu.KEY.KRS
                               && row["ABAAUFLFD"].ToString() == mu.KEY.LFD
                               && row["ABAAUFPOS"].ToString() == mu.KEY.POS
                               && row["ABAAPOS"].ToString() == ABAAPOS
                               select row;
                    foreach (DataRow row in qExt)
                    {
                        row["ABAVKFARBE"] = batches;//分缸数
                        row["ABAVKART"] = targetmqty;//单盘重量
                        INTEXDBC.UpdateABAUFM(row, 3);
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }
        private void btnAddBatch_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwMaster == null)
                {
                    MessageBox.Show("请选择生产单行");
                    return;
                }
                if (BatchQty == 0)
                {
                    MessageBox.Show("请确定分盘(产品)数量");
                    return;
                }
                int batchnum = 1;
                NewBatch(BatchQty, 1);//增加一个分批时，分缸数是1;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                btnQuery_Click(null, null);
            }
        }

        private void btnSaveBatch_Click(object sender, RoutedEventArgs e)
        {
            if (dwMU == null)
                return;
            UpdateBatches(Batches);
        }
        private void btnManualSetQty_Click(object sender, RoutedEventArgs e)
        {
            double batches = Convert.ToDouble(dwMU["ABAVKFARBE"].ToString());
            double ABARESMG = Convert.ToDouble(dwMU["ABARESMG"].ToString());
            double batchqty = Math.Round((ABARESMG / 10) / batches, 0) * 10;
            dwMU["ABAVKART"] = Helpers.Helper.Left(batchqty.ToString().PadRight(20), 20);//单盘重量
            INTEXDBC.UpdateABAUFM(dwMU, 3);
        }

        private void btnHelp_Click(object sender, RoutedEventArgs e)
        {
            if (ZoneHelp.Visibility == Visibility.Collapsed)
            {
                ZoneHelp.Visibility = Visibility.Visible;
            }
            else
            {
                if (ZoneHelp.Visibility == Visibility.Visible)
                {
                    ZoneHelp.Visibility = Visibility.Collapsed;
                }
            }
        }

      
   

        private void btnAddGAAUF_Click(object sender, RoutedEventArgs e)
        {
            if (dwGAAUF == null)
            {
                MessageBox.Show("请选择一条最相近的记录");
                return;
            }
            DataRow dwData = SetDetail.Tables["GAAUF"].Rows.Add();
            dwData.ItemArray = dwGAAUF.ItemArray;
            var gapos = (from DataRow row in SetDetail.Tables["GAAUF"].AsEnumerable()
                         select row["GAPOS"].ToString())
                      .Max();
            int POS = Convert.ToInt16((string)gapos);
            dwData["GAPOS"] = Helpers.Helper.Right("00" + (POS + 1), 2);
            if (vwGAAUF.View != null)
            {
                vwGAAUF.View.MoveCurrentToLast();
            }
        }
        private void btnSaveGAAUF_Click(object sender, RoutedEventArgs e)
        {
            if (dwGAAUF == null)
            {
                MessageBox.Show("请选择要保存的纱线");
                return;
            }
            foreach (DataRow row in SetDetail.Tables["GAAUF"].Rows)
            {
                row["GAART"] = Helpers.Helper.Left(row["GAART"].ToString().PadRight(20), 20);
                row["GAVAR"] = Helpers.Helper.Left(row["GAVAR"].ToString().PadRight(3), 3);
                row["GAFARBE"] = Helpers.Helper.Left(row["GAFARBE"].ToString().PadRight(10), 10);
                row["GABEM"] = Helpers.Helper.Left(row["GABEM"].ToString().PadRight(40), 40);
                DataSet SResult = INTEXDBC.QueryGSCOLOR(row, 5);
                if (SResult.Tables[0].Rows.Count == 0)
                {
                    MessageBox.Show("纱线不存在，请核对编码");
                    continue;
                }
                INTEXDBC.SaveGAAUF(row, "YGR");
            }
        }

        private void Calculate_Click(object sender, RoutedEventArgs e)
        {
            foreach (DataRow GA in SetDetail.Tables["GAAUF"].Rows)
            {
                double MRatio = Convert.ToDouble(GA["GABASMG2"].ToString()) * 0.01 * 0.001;
                GA["GAKG1"] = System.Math.Round(ABPQTY * MRatio, 2) * 100;
            }
        }
        private void txtRatio_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key != Key.Enter && e.Key != Key.Return)
                return;
        }
        private void btnDelGAAUF_Click(object sender, RoutedEventArgs e)
        {
            if (dwGAAUF == null)
            {
                MessageBox.Show("请选择要保存的纱线");
                return;
            }
            INTEXDBC.DeleteGAAUF(dwGAAUF, 1);
            btnQuery_Click(null, null);
        }

        private void btnToAllocation_Click(object sender, RoutedEventArgs e)
        {
            
        }
    }
}
